package com.ybu.oodd.utils.time;

import com.ybu.oodd.controller.AIController;
import com.ybu.oodd.pojo.HomeNum;
import com.ybu.oodd.service.HomeService;
import com.ybu.oodd.service.UserService;
import com.ybu.oodd.utils.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

@Component
@Slf4j
public class ScheduledTaskService {

    @Autowired
    private HomeService homeService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 每5分钟执行一次
     * cron 表达式：秒 分 时 日 月 周
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void Active() {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("✅ Active 定时任务执行：每5分钟一次，当前时间: {}", currentTime);
        // mysql  查询homenum
        HomeNum homeNum = homeService.getHomeNumByMysql();
        // 5m
        redisUtil.hset("homeNum","totalUsers",homeNum.getTotalUsers().toString(),310L);
        redisUtil.hset("homeNum","onlineUsers",homeNum.getOnlineUsers().toString(),310L);
        redisUtil.hset("homeNum","companyCount",homeNum.getCompanyCount().toString(),310L);
        redisUtil.hset("homeNum","jobCount",homeNum.getJobCount().toString(),310L);
        redisUtil.hset("homeNum","deliveredCount",homeNum.getDeliveredCount().toString(),310L);
    }

    @Scheduled(cron = "0 0 */6 * * ?")
//    @Scheduled(cron = "*/10 * * * * ?")
    public void Vip() {
        String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("✅ Vip 定时任务执行：每5分钟一次，当前时间: {}", currentTime);
        List<Integer> list = userService.getVipUserId();
        redisUtil.set("vip",list);

        List<Map<Integer, Integer>> freeUserId = userService.getFreeUserId();
        freeUserId.forEach(map -> {
            redisUtil.hset("free",map.get("id").toString(),map.get("free_num").toString());
        });
    }

    @Value("${file.upload-dir}")
    private String uploadDir;  // 对应 templates

    @Value("${file.static-dir}")
    private String staticDir;  // 对应 static

    @Scheduled(cron = "0 0 */1 * * ?") // 每小时执行一次
    public String refreshTemplate() {
        try {
            Path templatesDir = Paths.get(uploadDir);
            Path staticDirPath = Paths.get(staticDir);

            // 确保目录存在（可选，根据需求）
            if (!Files.exists(staticDirPath)) {
                return "Error: static directory not found: " + staticDirPath;
            }

            // 创建 templates 目录（如果不存在）
            Files.createDirectories(templatesDir);

            // 删除 templates 下所有文件
            try (Stream<Path> files = Files.list(templatesDir)) {
                files.forEach(file -> {
                    try {
                        if (Files.isRegularFile(file)) {
                            Files.delete(file);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("Failed to delete file: " + file, e);
                    }
                });
            }

            // 复制 static/a.pdf → templates/a.pdf
            Path sourcePdf = staticDirPath.resolve("a.pdf");
            Path destPdf = templatesDir.resolve("a.pdf");

            if (!Files.exists(sourcePdf)) {
                return "Error: a.pdf not found in static directory: " + sourcePdf;
            }

            Files.copy(sourcePdf, destPdf, StandardCopyOption.REPLACE_EXISTING);

            return "Success: Refreshed templates with a.pdf from static";

        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }
}